package com.ias.agdis_r.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;

import com.ias.agdis_r.bean.other.AppVName;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.MessageModel;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串助手类
 * 
 * @author wuguiyu,wanghu
 * 
 */
@SuppressLint("NewApi")
public class S {

	/**
	 * 获取应用版本号
	 */
	public static String getAppVersion() {
		PackageInfo pkg;
		String versionName = "";
		try {
			String packName = DataBaseManager.getInstance().getContext().getPackageName();
			pkg = DataBaseManager.getInstance().getContext().getPackageManager().getPackageInfo(packName, 0);
			versionName = pkg.versionName; 
		} catch (NameNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		} 
		
		return versionName;
	}

	/**
	 * 连接字符串
	 * **/
	public static String contact(Object... args) {
		StringBuffer s = new StringBuffer();
		for (Object arg : args) {
			s.append(arg);
		}
		return s.toString();
	}

	/*
	 * 在某字段前插入字符串
	 * */
	public static String insertBeforeTxt(String _sSrc, String _sInsert, String _sTxt) {
		String sChanged = _sSrc;
		int nIndex = _sSrc.indexOf(_sTxt);
		if (nIndex != -1) {
			String sHead = _sSrc.substring(0,nIndex);
			String sTail = _sSrc.substring(nIndex,_sSrc.length());
			sChanged = sHead + _sInsert + "," +sTail;	
		}
		return sChanged;
	}
	
	/**
	 * 判断字符串是否为空
	 * 
	 * @str 需要判断的字符串
	 * @return true:为空，false：不为空
	 * **/
	public static boolean isEmpty(String str) {
		return str == null || "".equals(str);
	}

	/**
	 * 判断字符串是否不为空
	 * 
	 * @str 需要判断的字符串
	 * @return true:不为空，false：为空
	 * **/
	public static boolean isNotEmpty(String str) {
		return !isEmpty(str);
	}

	public static String valueOf(Object o) {
		String result = "";
		if (o != null) {
			result = o.toString();
		}
		return result;
	}

	/**
	 * IP地址合法性效验
	 * 
	 * @param str
	 *            需要验证的IP地址
	 * @return true：合法，false：不合法
	 */
	public static boolean isIpAddress(String str) {
		String regex = "(((2[0-4]\\d)|(25[0-5]))|(1\\d{2})|([1-9]\\d)|(\\d))[.](((2[0-4]\\d)|(25[0-5]))|(1\\d{2})|([1-9]\\d)|(\\d))[.](((2[0-4]\\d)|(25[0-5]))|(1\\d{2})|([1-9]\\d)|(\\d))[.](((2[0-4]\\d)|(25[0-5]))|(1\\d{2})|([1-9]\\d)|(\\d))";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(str);
		return m.matches();

	}
	
	/**
	 * PORT地址合法性效验
	 * 
	 * @param str
	 *            需要验证的PORT地址
	 * @return true：合法，false：不合法
	 */
	public static boolean isPort(String str) {
		
		try {
			
			int n = Integer.parseInt(str);
			if(n >= 1 && n <= 65535){
				
				return true;
			}
			
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 数字效验
	 * 
	 * @param str
	 * @return true：是数字，并且第一位不能为0；false：非数字
	 */
	public static boolean isNumber(String str) {
		if (isEmpty(str))
			return false;
		char s[] = str.toCharArray();
		for (int i = 0; i < s.length; i++) {
			if (s[i] < '0' || s[i] > '9' || '0' == s[0])
				return false;
		}
		return true;
	}

	public static boolean isJobNumber(String str) {
		if (isEmpty(str))
			return false;
		char s[] = str.toCharArray();
		for (int i = 0; i < s.length; i++) {
			if (s[i] < '0' || s[i] > '9')
				return false;
		}
		return true;
	}
	
	private static int mPreNum = 0;

	/**
	 * 获取自增长数
	 * 
	 * @return
	 */
	public static String getAutoIncrementNum() {
		int mLastNum = mPreNum + 1;
		int len = (mLastNum + "").length();
		String resultStr;

		if (len < 2) {
			resultStr = "0000" + mLastNum;
		} else if (len < 3) {
			resultStr = "000" + mLastNum;
		} else if (len < 4) {
			resultStr = "00" + mLastNum;
		} else if (len < 5) {
			resultStr = "0" + mLastNum;
		} else if (len < 6) {
			resultStr = "" + mLastNum;
		} else {
			mLastNum = 1;
			resultStr = "0000" + mLastNum;
		}

		mPreNum = mLastNum;

		return resultStr;
	}

	/**
	 * 获取校验码
	 * 
	 * @param str
	 * @return
	 */
	public static String getCheckCode(String str) {
		char[] chars = str.toCharArray();
		int m = 0;
		for (int i = 0; i < chars.length; i++) {
			if (i == 0) {
				m = (int) chars[0];
			} else {
				m ^= (int) chars[i];
			}
		}
		m = m % 255;
		String  result = Integer.toHexString(m).toUpperCase();
		//如果只有一位前面补0
		if(result.length()==1)
		{
			result ="0"+result;
		}
		return result;
	}

	/**
	 * 获取TXT文本内容,（使用byte的length）
	 * 
	 * @param message
	 * @return
	 */
	public static String getTXTContent(String message,int txtlength)
	{
		int _start = message.indexOf("TXT");
		String TXT = "";
		try {
			TXT = mySubString(message,_start+3,message.length());
			TXT = bSubstring(TXT,txtlength);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			TXT = "";
		}
		return TXT;
	}
	
	/**   
	 * 获取字符串的长度
	 * @param s 要截取的字符串   
	 * return 返回length(int)
	*/   
	public static int getStringLen(String s)
	   {    	   
			try
			{
				if(s.isEmpty())
				{
					return 0;
				}
				
				int len = 0;
				len   =   s.getBytes("GBK").length;
					
				return len;
			
			} catch (Exception e) {
				// TODO Auto-generated catch block
				
				e.printStackTrace();
				return 0;
			}
	   }   
	   
	   
	/**   
	 * 按字节长度截取字符串
	 * @param message 要截取的字符串
	 * @param length 要截取字符串的长度->是字节一个汉字2个字节   
	 * return 返回length长度的字符串（含汉字）   
	*/   
	   public static String bSubstring(String message, int length)
	   {
		   try {
			   byte[] messageGBK = message.getBytes("GBK");
			   return new String(Arrays.copyOfRange(messageGBK, 0, length), "GBK");
		   } catch (UnsupportedEncodingException e) {
			   e.printStackTrace();
			   return "";
		   }
	   }   

	   
	/**
	 * SubString捕获StringIndexOutOfBoundsException异常
	 * 
	 * @param _str
	 * @param _start
	 * @param _end
	 * @return
	 */
	public static String mySubString(String _str, int _start, int _end) {
		String result = null;
		try {
			result = _str.substring(_start, _end);
		} catch (StringIndexOutOfBoundsException e) {
			result = null;
		}
		return result;
	}
	
	/**
	 * 获取航班显示时间
	 * 
	 * @return
	 */
	public static String getFlightLatestTime(String _sATO, String _sETO, String _sSTO) {
		String sTime = "";
		if (!_sATO.isEmpty()) {
			sTime = _sATO;
		} else if (!_sETO.isEmpty()) {
			sTime = _sETO;
		} else if (!_sSTO.isEmpty()) {
			sTime = _sSTO;
		}
		return sTime;
	}
	
	/**
	 * 获取当前系统日期时间
	 * 
	 * @author by zhangsc 
	 * @return 数字格式的日期时间
	 */
	public static String getNowTime()
	{
		Date nowtime=new Date();
		SimpleDateFormat matter;
		matter=new SimpleDateFormat("yyyyMMddHHmmss");
		matter.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
		
		return matter.format(nowtime);
		
	}
	/**
	 * 获取当前系统日期时间
	 * 
	 * @author by zhangsc 
	 * @return 日志格式的日期时间
	 */
	public static String getNowTime2()
	{
		Date nowtime=new Date();
		SimpleDateFormat matter;
		matter=new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]:");
		matter.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); 
		
		return matter.format(nowtime);
		
	}
	
	public static String getNowTime3()
	{
		Date nowtime=new Date();
		SimpleDateFormat matter;
		matter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		matter.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
		
		return matter.format(nowtime);
		
	}

	public static String getNowTime4()
	{
		SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
		Date curDate = new Date(System.currentTimeMillis());
		return formatter.format(curDate);
	}
	
	public static String getPsn(String _sList) {
		String sPsn = null;
		int nStart = _sList.indexOf("[");
		int nEnd = _sList.indexOf("]");
		if (nStart > -1 && nEnd > -1) {
			sPsn = _sList.substring(nStart+1, nEnd);
		}
		return sPsn;
	}

	public static String getResType(String _sList) {
		String sResType = null;
		int nStart = _sList.indexOf("[");
		int nEnd = _sList.indexOf("]");
		if (nStart > -1 && nEnd > -1) {
			sResType = _sList.substring(0, nStart);
		}
		return sResType;
	}
	
	public static String getAPPVN(Context context){
		AppVName.getAppVName(context);
		return AppVName.aName == null?"none":AppVName.aName;
	}
	
	/**
	 * 启动Activity
	 * zhangsc
	 */
	public static void startActivity(Class activityClass){

		Context context = DataBaseManager.getInstance().getContext();
		Intent startIntent = new Intent(context,activityClass);
		startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(startIntent);
	}
	/**
	 *	字符串替换
	 *  @author by zhaoyj
	 */
	public static String replace(String strSource, String strFrom, String strTo) {    
	    if (strSource == null) {        
	      return null;    
	    }  
	    int i = 0;
	    if ((i = strSource.indexOf(strFrom, i)) >= 0) {
	      char[] cSrc = strSource.toCharArray();
	      char[] cTo = strTo.toCharArray();
	      int len = strFrom.length();  
	      StringBuffer buf = new StringBuffer(cSrc.length);  
	      buf.append(cSrc, 0, i).append(cTo);
	      i += len;    
	      int j = i;       
	      while ((i = strSource.indexOf(strFrom, i)) > 0) {  
	        buf.append(cSrc, j, i - j).append(cTo);   
	        i += len;  
	        j = i;        
	      }        
	      buf.append(cSrc, j, cSrc.length - j); 
	      return buf.toString(); 
	    } 
	    return strSource;
	  } 
	
	public static String getLockNum(String _sList) {
		String sPsn = null;
		int nStart = _sList.indexOf("[");
		int nEnd = _sList.indexOf("]");
		if (nStart > -1 && nEnd > -1) {
			sPsn = _sList.substring(nStart+1, nEnd);
		}
		return sPsn;
	}
	
	public static String getLockType(String _sList) {
		String sPsn = null;
		int nEnd = _sList.indexOf(",");
		if (nEnd > -1) {
			sPsn = _sList.substring(nEnd);
		}
		return sPsn;
	}

	public static String getCDATA(String txt){
		String end = MessageModel.SCDATA + txt + MessageModel.ECDATA;
		return end;
	}

	public static String getCDATAInfo (String txt){
		String info = "";
		try {
			if(S.isNotEmpty(txt))
			{
				int sindex = txt.indexOf(MessageModel.SCDATA);
				int eindex = txt.indexOf(MessageModel.ECDATA);
				
				info = txt.substring(sindex+MessageModel.SCDATA.length(),eindex);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return info;
	}
	
	public static String FormatTime(String time) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			java.util.Date ctime;
			ctime = sdf.parse(time);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(ctime);
			return calendar.get(Calendar.HOUR_OF_DAY) + ""
					+ calendar.get(Calendar.MINUTE);
		} catch (Exception e) {
			return "";
		}

	}
	
	public static String FormatTime2(String time) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date ctime = sdf.parse(time);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(ctime);
			String hour = String.valueOf(calendar.get(Calendar.HOUR_OF_DAY));
			if (hour.length() < 2) {
				hour = "0" + hour;
			}
			String minute = String.valueOf(calendar.get(Calendar.MINUTE));
			if (minute.length() < 2) {
				minute = "0" + minute;
			}

			return hour + minute+daysBetween(ctime,new Date());
		} catch (Exception e) {
			return "";
		}

	}

	public static String FormatTimeHCCMonitorNoExe(String time) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date ctime = sdf.parse(time);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(ctime);
			String hour = String.valueOf(calendar.get(Calendar.HOUR_OF_DAY));
			if (hour.length() < 2) {
				hour = "0" + hour;
			}
			String minute = String.valueOf(calendar.get(Calendar.MINUTE));
			if (minute.length() < 2) {
				minute = "0" + minute;
			}

			return hour + minute+daysBetween(ctime,new Date());
		} catch (Exception e) {
			return time;
		}
	}

	/**
	 * 计算两个日期相差天数
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static String daysBetween(Date date1,Date date2)  
    {  
        String sresult = "";
        int result = 0;
        
        try {
			Calendar cal = Calendar.getInstance(); 
			cal.setTime(date1);
			int day1 = cal.get(Calendar.DAY_OF_YEAR);
			int year1 = cal.get(Calendar.YEAR);
			cal.setTime(date2);
			int day2 = cal.get(Calendar.DAY_OF_YEAR);
			int year2 = cal.get(Calendar.YEAR);
			if(year1-year2>0)
			{
				String lastYear = year1+"-12-31";
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date lastYearDate = sdf.parse(lastYear);
				cal.setTime(lastYearDate);
				int countDay = cal.get(Calendar.DAY_OF_YEAR);
				result = day1 +countDay -day2;
				
				sresult = "";
			}
			else if(year2-year1>0)
			{
				String lastYear = year2+"-12-31";
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date lastYearDate = sdf.parse(lastYear);
				cal.setTime(lastYearDate);
				int countDay = cal.get(Calendar.DAY_OF_YEAR);
				result = -(day2 + countDay -day1);
			}
			else
			{
			    result = day1-day2;
			}
			
			
			if(result > 0)
			{
				if(result == 1)
				{
					sresult = "+";
				}
				else
				{
					sresult = "+" + result;
				}
			}
			else if(result == 0)
			{
				sresult = "";
			}
			else
			{
				if(result == -1)
				{
					sresult = "-";
				}
				else
				{
					sresult = result +"";
				}
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       return sresult;         
    }  

	public static byte[] readFileByByte(File file) {

		BufferedInputStream bufferedInputStream = null;
		int readCount = 0;
		byte[] temp = new byte[100];
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

		try {
			bufferedInputStream = new BufferedInputStream(new FileInputStream(
					file));
			while ((readCount = bufferedInputStream.read(temp)) != -1) {
				byteArrayOutputStream.write(temp, 0, readCount);
			}
			return byteArrayOutputStream.toByteArray();
		} catch (Exception e) {
		}
		finally
		{
			if(bufferedInputStream!=null)
			{
				try {
					bufferedInputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return null;
	}
	
	/**
	 * 判断字符串是否是一个IP
	 * @param addr
	 * @return
	 */
	public static boolean isIP(String addr)
    {
      if(addr.length() < 7 || addr.length() > 15 || "".equals(addr))
      {
        return false;
      }
      /**
       * 判断IP格式和范围
       */
      String rexp = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
              + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
              + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
              + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
      
      Pattern pat = Pattern.compile(rexp);  
      
      Matcher mat = pat.matcher(addr);  
      
      boolean ipAddress = mat.find();

      return ipAddress;
    }

	/**
	 * 验证字符串是否为数字
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(CharSequence str){
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if(!isNum.matches()){
			return false;
		}
		return true;
	}

	/**
	 * 检测APP状态，如果已经安装且未运行，返回false
	 *
	 * @param packName
	 * @return
	 */
	public static boolean checkAppInstall(String packName) {
		if (packName == null || "".equals(packName))
			return false;
		try {
			DataBaseManager.getInstance().getContext().getPackageManager().getApplicationInfo(packName,
					PackageManager.GET_UNINSTALLED_PACKAGES);
			return true;
		} catch (NameNotFoundException e) {
			return false;
		}
	}

	public static String getPhotoName(String subName){
		String enb = "";
		try {
			enb = JavaBeanManager.getInstance().getUserinfo().getEnb();
		} catch (Exception e) {
			e.printStackTrace();
		}
		String photoName = S.getNowTime();
		if(S.isNotEmpty(subName)){
			photoName = photoName+ "_"+subName;
		}
		if(S.isNotEmpty(enb)){
			photoName = photoName+ "_"+ enb;
		}
		photoName = photoName + ".jpg";
		return photoName;
	}
}
